//
//  SearchViewController.m
//  kr_36
//
//  Created by lmt on 16/1/26.
//  Copyright © 2016年 www.lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "SearchViewController.h"
#import "LMTAFNetwork.h"
#import "NewsModel.h"
#import "NewsDetailViewController.h"


@interface SearchViewController ()<UISearchResultsUpdating, UISearchBarDelegate,UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain) UISearchController *search;/**< 搜索控制视图 */
@property (nonatomic, copy) NSString *strHight;/**< 高亮用字符串 保存搜索信息 */
@property (nonatomic, retain) NSMutableArray *companyArr;/**< 搜索到公司数组 */

@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) UIView *tempView;
@property (nonatomic, assign) NSInteger i;


@end

@implementation SearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    // 创建tableView
    [self createTableView];
    
    // 初始化搜索视图
    self.search = [[UISearchController alloc] initWithSearchResultsController:nil];
    // 签订协议
    _search.searchResultsUpdater = self;
    
    // 屏幕不变灰 yes时tableview 不能下拉
    _search.dimsBackgroundDuringPresentation = NO;
    
    // 设置点击搜索框时隐藏导航栏
    _search.hidesNavigationBarDuringPresentation = NO;
    
    // 位置自适应
    [_search.searchBar sizeToFit];

    //_search.searchBar.frame = CGRectMake(self.search.searchBar.frame.origin.x, self.search.searchBar.frame.origin.y, self.search.searchBar.frame.size.width, 44.0);
    
    // 把搜索视图加载导航栏上
    self.navigationItem.titleView = _search.searchBar;

    //self.tableView.tableHeaderView = self.search.searchBar;
    
    
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:(UIBarButtonItemStylePlain) target:self action:@selector(back)];
    self.navigationItem.leftBarButtonItem = leftItem;
    
}

- (void)back
{
    
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}


- (void)createTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:(UITableViewStylePlain)];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
}

#pragma mark - 实现搜索栏协议方法
// 知道搜索栏有内容 就执行下面的方法
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController
{

    
    // 将搜索内容转化为字符串
    // 等同于 获取搜索的信息
    self.strHight = [self.search.searchBar text];
    
    if ([_strHight containsString:@" "]) {
        
        // 字符串有空格的时候 搜索会崩溃
        // 判断如果有空格不执行
        // 没有执行以下程序
        
    } else {
        
        // 拼接
        NSString *urlStr = [_strHight stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:_strHight]];
        // 中文转码
        NSString *str = [NSString stringWithFormat:@"https://rong.36kr.com/api/mobi/news/search?keyword=%@&page=%ld&pageSize=20", urlStr, _i];
        
        [LMTAFNetwork postUrlString:str body:nil response:LMTJSON bodyStyle:RequestJSON requestHeadFile:nil success:^(NSURLSessionDataTask *task, id responseObject) {
            
            NSMutableArray *arr = responseObject[@"data"][@"data"];
            self.companyArr = [NewsModel modelHanderWithArray:arr];
            [_tableView reloadData];
            
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            NSLog(@"zxc");
        }];
    }
    
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _companyArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
    NewsModel *m = _companyArr[indexPath.row];
    
    ///高亮设置
    NSMutableAttributedString *attrituteString = [[NSMutableAttributedString alloc] initWithString:m.title];
    NSRange range = [m.title rangeOfString:_strHight];
    [attrituteString setAttributes:@{NSForegroundColorAttributeName : [UIColor redColor],   NSFontAttributeName : [UIFont systemFontOfSize:18]} range:range];
    
    cell.textLabel.attributedText = attrituteString;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NewsModel *m = _companyArr[indexPath.row];
    
    NewsDetailViewController *ndVC = [[NewsDetailViewController alloc] init];
    
    ndVC.str = m.feedId;
    
    [self.navigationController pushViewController:ndVC animated:YES];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
